/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import dto.LoggedUser;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import util.Constants;
import util.DBConnection;

/**
 *
 * @author Shuvo
 */
public class AskQuestion extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String subject = request.getParameter("subject");
        String text = request.getParameter("text");
        HttpSession session = request.getSession();
        String redirectUrl = "/discuss.jsp";

        try {
            Connection con = DBConnection.getConn();
            LoggedUser loggedUser = (LoggedUser) session.getAttribute("user");
            if (con != null && loggedUser != null) {
                String askedBy = loggedUser.getUserId();
                String type = loggedUser.getType();
                Statement statement = con.createStatement();
                String status = Constants.Open;
                String reviewedBy = null;
                if(Constants.Faculty.equalsIgnoreCase(type)) {
                    status = Constants.Approved;
                    reviewedBy = loggedUser.getUserId();
                }
                String query = "insert into QUESTION values (QUES_SEQ.NEXTVAL,'" + text + "','" + subject + "','" + askedBy + "', to_char(sysdate, 'dd/Mon/yyyy hh:mi:ssam'), '" + status + "', "+reviewedBy+")";
                int i = statement.executeUpdate(query);
                if (i == 1 && Constants.Student.equalsIgnoreCase(type)) {
                    session.setAttribute("ask", "Success");
                }
                statement.close();
                con.close();
            }
        } catch (Exception e) {
            session.setAttribute("ask", "Error");
            e.printStackTrace();
        }
        response.sendRedirect(request.getContextPath() + redirectUrl);
    }
}
